﻿var Usageself = this;
var PaidVersion = true;
var camlQuery = new SP.CamlQuery.createAllItemsQuery();
Usageself.hostWebUrl = "";
Usageself.appWebContext = null;
Usageself.hostWebContext = null;
Usageself.hostWeb = null;
Usageself.item = null;
Usageself.list = null;
Usageself.currentUser = null;

$(document).ready(function () {
    Usageself.hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    Usageself.appWebContext = new SP.ClientContext.get_current();
    Usageself.hostWebContext = new SP.AppContextSite(Usageself.appWebContext, Usageself.hostWebUrl);
    Usageself.hostWeb = hostWebContext.get_web();
    Usageself.list = Usageself.hostWeb.get_webs();
    Usageself.currentUser = Usageself.hostWeb.get_currentUser();
    Usageself.appWebContext.load(Usageself.list);
    Usageself.appWebContext.load(Usageself.currentUser);
    Usageself.appWebContext.executeQueryAsync(Usageself.GetInfo, Usageself.onError);
});

Usageself.GetInfo = function () {
    var itemEnumerator = Usageself.list.getEnumerator();
    while (itemEnumerator.moveNext()) {
        if (itemEnumerator.get_current().get_title() == "SharePoint Permission Explorer") {
            Usageself.list = itemEnumerator.get_current().get_lists().getByTitle("UserRegister");
            Usageself.appWebContext.load(Usageself.list);
            Usageself.appWebContext.executeQueryAsync(Usageself.GetList, Usageself.onError);
        }

    }

}

Usageself.GetList = function () {
    if (Usageself.list.get_itemCount() != 0) {
        Usageself.item = Usageself.list.getItemById(1);
        Usageself.appWebContext.load(Usageself.item);
        Usageself.appWebContext.executeQueryAsync(Usageself.LoadItem, StartApp);
    }
    else {
        var item = Usageself.list.addItem();
        item.set_item("User1", Usageself.currentUser);
        item.set_item("id", 1);
        item.set_item("Version", "Trial");
        PaidVersion = true;
        item.update();
        Usageself.appWebContext.load(item);
        Usageself.appWebContext.executeQueryAsync(StartApp, StartApp);
    }
}

Usageself.LoadItem = function () {
    var itemEnumerator = Usageself.item.getEnumerator();
    while (itemEnumerator.moveNext()) {
        Usageself.item=itemEnumerator.get_current();
    }
    if (Usageself.item.get_item("Version") == "Trial") {
        PaidVersion = true;
    }
    else {
        PaidVersion = true;
    }
    StartApp();
}


Usageself.onError = function () {
    alert("notWorking");
}

